<template>
    <div class="edit-popup">
        <popup
            ref="popupRef"
            :title="popupTitle"
            :async="true"
            width="1000px"
            @confirm="handleSubmit"
            @close="handleClose"
        >
            <el-form ref="formRef" :model="formData" label-width="108px" :rules="formRules">
                <el-form-item label="房间标题" prop="name">
                    <el-input v-model="formData.name" clearable placeholder="请输入房间标题" />
                </el-form-item>
                
                <el-form-item label="房间封面" prop="cover">
                    <!-- <el-input v-model="formData.cover" clearable placeholder="请输入图片" :disabled="true"/> -->
                    <material-picker v-model="formData.cover" :limit="1" />
                </el-form-item>
                <el-form-item label="价格" prop="price">
                    <el-input v-model="formData.price" clearable placeholder="请输入价格" />
                </el-form-item>
                <el-form-item label="房间数量" prop="number">
                    <el-input-number v-model="formData.number" :min="0" clearable placeholder="请输入房间数量" />
                </el-form-item>
                <el-form-item label="轮播图" prop="photos">
                    <!-- <el-input v-model="formData.cover" clearable placeholder="请输入图片" :disabled="true"/> -->
                    <material-picker v-model="formData.photos" :limit="99" />
                </el-form-item>
                <el-form-item label="视频" prop="video">
                    <!-- <el-input v-model="formData.cover" clearable placeholder="请输入图片" :disabled="true"/> -->
                    <material-picker v-model="formData.video" :limit="1" type="video" />
                </el-form-item>
                <el-form-item label="房间类型" prop="type">
                    <el-radio-group v-model="formData.type">
                        <el-radio :label="1">山也客房</el-radio>
                        <el-radio :label="2">宠物友好房</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="基础配置信息" prop="config">
                    <div class="config-form">
                        <div v-for="(item, index) in configItems" :key="index" class="config-item">
                            <material-picker v-model="item.icon" :limit="1" width="60px" height="60px"/>
                            <el-input
                                v-model="item.text"
                                placeholder="请输入内容，如：单人床 1米2"
                                class="config-value-input"
                                @blur="blurConfigText"
                            />
                            <el-button type="danger" icon="Delete" circle @click="removeConfigItem(index)" />
                        </div>
                        <el-button type="primary" @click="addConfigItem">添加配置项</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="服务项" prop="basic_config">
                    <el-checkbox-group v-model="formData.basic_config" size="small">
                        <el-checkbox  border v-for="item in hotelBasicList" :key="item.id" :label="item.title" :value="item.id" style="margin-bottom: 10px;"/>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="其他服务" prop="other_config">
                    <!-- 这里是其他服务，数组，每一项由一个标题输入框和文本框组成 -->

                    <div class="otherConfig-form">
                        <div v-for="(item, index) in otherConfigItems" :key="index" class="otherConfig-item">
                            <div class="otherConfig-item-info">
                                <el-input
                                    v-model="item.title"
                                    placeholder="请输入标题"
                                    class="otherConfig-title-input"
                                    @blur="blurOtherConfigText"
                                />
                                <el-input
                                    v-model="item.text"
                                    type="textarea"
                                    :rows="4"
                                    placeholder=""
                                    class="otherConfig-text-input"
                                    @blur="blurOtherConfigText"
                                />
                            </div>
                            
                            <el-button type="danger" icon="Delete" circle @click="removeOtherConfigItem(index)" style="width: 30px;height: 30px;"/>
                        </div>
                        <el-button type="primary" @click="addOtherConfigItem">添加配置项</el-button>
                    </div>
                </el-form-item>
                <el-form-item label="简介" prop="desc">
                    <el-input v-model="formData.desc" clearable placeholder="请输入简介" />
                    <!-- 这里用富文本编辑器 -->
                    <!-- <editor v-model="formData.desc" height="400px" /> -->
                </el-form-item>

                <!-- <el-form-item label="" prop="addtime">
                    <el-input v-model="formData.addtime" clearable placeholder="请输入" />
                </el-form-item>
                <el-form-item label="" prop="uptime">
                    <el-input v-model="formData.uptime" clearable placeholder="请输入" />
                </el-form-item> -->

            </el-form>
        </popup>
    </div>
</template>

<script lang="ts" setup name="roomEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiRoomAdd, apiRoomEdit, apiRoomDetail } from '@/api/room'
import { apiHotelBasicAll } from '@/api/hotel'
import { timeFormat } from '@/utils/util'
import type { PropType } from 'vue'
import { ref, computed, onMounted, reactive, shallowRef } from 'vue'
import Editor from '@/components/editor/index.vue'
// 定义配置项接口
interface ConfigItem {
    icon: string;
    text: string;
}

// 定义配置对象接口
interface ConfigObject {
    [key: string]: string;
}

defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')

// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑房间表' : '新增房间表'
})


// 表单数据
const formData = ref<any>({
    id: '',
    name: '',
    price: '',
    number: 1,
    cover: '',
    photos: '',
    video: '',
    type: 1,
    desc: '',
    config: '',
    basic_config: [],
    other_config: '',
})

// 表单验证
const formRules = reactive<any>({
    name: [{
        required: true,
        message: '请输入房间标题',
        trigger: ['blur']
    }],
    cover: [{
        required: true,
        message: '请上传封面',
        trigger: ['blur']
    }],
    photos: [{
        required: true,
        message: '请上传轮播图图片',
        trigger: ['blur']
    }],
    price: [{
        required: true,
        message: '请输入价格',
        trigger: ['blur']
    }],
    video: [{
        required: true,
        message: '请上传视频',
        trigger: ['blur']
    }],
    
    number: [{
        required: true,
        message: '请输入房间数量',
        trigger: ['blur']
    }],
    
    // type: [{
    //     required: true,
    //     message: '请选择房间类型',
    //     trigger: ['blur']
    // }],
    config: [{
        required: true,
        message: '请输入基础配置信息',
        trigger: ['blur']
    }],
})

// 配置项数组
const configText = ref('')
const configItems = ref<ConfigItem[]>([
    { icon: '', text: '' }
])

// 添加配置项
const addConfigItem = () => {
    configItems.value.push({ icon: '', text: '' })
}

// 删除配置项
const removeConfigItem = (index: number) => {
    configItems.value.splice(index, 1)
    if (configItems.value.length === 0) {
        configItems.value.push({ icon: '', text: '' })
    }
}
// 配置项失焦
const blurConfigText = () => {
    // const configObj: ConfigObject = {}
    // configItems.value.forEach(item => {
    //     if (item.icon && item.text) {
    //         configObj[item.icon] = item.text
    //     }
    // })
    formData.value.config = JSON.stringify(configItems.value)
    configText.value = JSON.stringify(configItems.value)
}
// 初始化配置项
const initConfigItems = (config: string | ConfigObject) => {
    try {
        const configObj = typeof config === 'string' ? JSON.parse(config) : config
        // configItems.value = Object.entries(configObj).map(([icon, text]) => ({
        //     icon,
        //     text: String(text)
        // }))
        configItems.value = configObj
        if (configItems.value.length === 0) {
            configItems.value.push({ icon: '', text: '' })
        }
    } catch (error) {
        console.error('解析配置信息失败:', error)
        configItems.value = [{ icon: '', text: '' }]
    }
}


// 其他服务
const otherConfigText = ref('')
const otherConfigItems = ref<any[]>([
    { title: '', text: '' }
])

// 添加配置项
const addOtherConfigItem = () => {
    otherConfigItems.value.push({ title: '', text: '' })
}

// 删除配置项
const removeOtherConfigItem = (index: number) => {
    otherConfigItems.value.splice(index, 1)
    if (otherConfigItems.value.length === 0) {
        otherConfigItems.value.push({ title: '', text: '' })
    }
}
// 其他服务失焦
const blurOtherConfigText = () => {
    // const configObj: ConfigObject = {}
    // otherConfigItems.value.forEach(item => {
    //     if (item.title && item.text) {
    //         configObj[item.title] = item.text
    //     }
    // })
    formData.value.other_config = JSON.stringify(otherConfigItems.value)
    otherConfigText.value = JSON.stringify(otherConfigItems.value)
}
// 初始化配置项
const initOtherConfigItems = (config: string | ConfigObject) => {
    try {
        const configObj = typeof config === 'string' ? JSON.parse(config) : config
        // otherConfigItems.value = Object.entries(configObj).map(([title, text]) => ({
        //     title,
        //     text: String(text)
        // }))
        otherConfigItems.value = configObj
        if (otherConfigItems.value.length === 0) {
            otherConfigItems.value.push({ title: '', text: '' })
        }
    } catch (error) {
        console.error('解析配置信息失败:', error)
        otherConfigItems.value = [{ title: '', text: '' }]
    }
}

// 在组件挂载时初始化配置项
onMounted(() => {
    
})

// 获取详情
const setFormData = async (data: Record<any, any>) => {
    for (const key in formData.value) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            if(key == 'basic_config'){
                let list = data[key].split(',')
                formData.value[key] = list.map((item: any) => Number(item))
            }else if(key == 'photos'){
                formData.value[key] = data[key].split(',')
            }else{
                formData.value[key] = data[key]
            }
        }
    }
    // 处理基础配置信息的显示
    if (formData.value.config) {
        initConfigItems(formData.value.config)  
        // try {
        //     // 尝试解析 JSON 字符串
        //     const configObj = JSON.parse(formData.value.config)
            
        //     // 格式化显示
        //     formData.value.config = JSON.stringify(configObj, null, 2)
        // } catch (e) {
        //     // 如果已经是对象，直接使用
        //     if (typeof formData.value.config === 'object') {
        //         formData.value.config = JSON.stringify(formData.value.config, null, 2)
        //     }
        //     // 否则直接显示原始值
        // }
    }
    // 其他服务
    if (formData.value.other_config) {
        initOtherConfigItems(formData.value.other_config)
    }
    
}

const getDetail = async (row: Record<string, any>) => {
    const data = await apiRoomDetail({
        id: row.id
    })
    setFormData(data)
}

// 提交按钮
const handleSubmit = async () => {
    await formRef.value?.validate()
    console.log('formData.value',toRaw(formData.value))
    let obj = JSON.parse(JSON.stringify(formData.value))
    if(formData.value.photos.length > 0){
        obj.photos = formData.value.photos.join(',')
    }
    // 确保 config 是有效的 JSON 字符串
    if (formData.value.config && typeof formData.value.config === 'string') {
        try {
            // 验证是否为有效的 JSON
            JSON.parse(formData.value.config)
        } catch (e) {
            // 如果不是有效的 JSON，尝试修复
            try {
                const configObj = JSON.parse(configText.value)
                obj.config = JSON.stringify(configObj)
            } catch (e) {
                console.error('配置信息格式错误，无法提交')
                return
            }
        }
    }
    // 其他服务
    if (formData.value.other_config) {
        try {
            // 验证是否为有效的 JSON
            JSON.parse(formData.value.other_config)
        } catch (e) {
            // 如果不是有效的 JSON，尝试修复
            try {
                const configObj = JSON.parse(otherConfigText.value)
                obj.other_config = JSON.stringify(configObj)
            } catch (e) {
                console.error('其他服务信息格式错误，无法提交')
                return
            }
        }
    }
    // 基础配置
    if (formData.value.basic_config.length > 0) {
        try {
            // 验证是否为有效的 JSON
            obj.basic_config = formData.value.basic_config.join(',')
        } catch (e) {
            // 如果不是有效的 JSON，尝试修复
            return ''
        }
    }
    
    const data = { ...obj }
    console.log('data==========================',data)
    mode.value == 'edit' 
        ? await apiRoomEdit(data) 
        : await apiRoomAdd(data)
    popupRef.value?.close()
    emit('success')
}

//打开弹窗
const open = (type = 'add') => {
    mode.value = type
    popupRef.value?.open()
    getApiHotelBasicAllFun()
}

// 关闭回调
const handleClose = () => {
    emit('close')
}

const hotelBasicList = ref<any[]>([])
const getApiHotelBasicAllFun = async () => {
    const res = await apiHotelBasicAll({})
    hotelBasicList.value = res
}


defineExpose({
    open,
    setFormData,
    getDetail
})
</script>

<style scoped>
.config-form {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.config-item {
    display: flex;
    gap: 10px;
    align-items: center;
}
.config-item-other{
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
}
.config-key-input {
    width: 200px;
}

.config-value-input {
    flex: 1;
}

.otherConfig-form {
    width: 100%;
    display: flex;
    flex-direction: column;
    gap: 10px;
}
.otherConfig-item{
    width: 100%;
    display: flex;
    gap: 10px;
    align-items: flex-end;
}
.otherConfig-item-info{
    width: calc(100% - 40px);
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
}
.otherConfig-text-input {
    flex: 1;
}
</style>
